<?php
require_once "Zen/View/Helper/Image/lib/WideImage.php";
class Zen_View_Helper_Image_Multi extends Zend_View_Helper_Abstract {
	
	protected $actions = array ();
	protected $imagesId = false;
	protected $images = false;
	protected $type;
	protected $quality = 100;
	protected $page=1;
	protected $pagecount=1;
	protected $first_only = false;
	protected $show_dim = false;
	protected $alts = array();
	
	protected function init($params) {
		$this->actions = array ();
		$this->imagesId = false;
		$this->images = false;
		$this->quality = ( isset($params['quality'])) ? $params['quality'] : $this->quality;
		$this->page=1;
		$this->pagecount=1;
		$this->first_only = false;
	}
	
	public function image_Multi($field, $params=array() ) {
		$this->init($params);
		if (! $field ) return $this;
		$ids = explode ( ',', $field ); 
		if (! count($ids) ) return $this;
		foreach ( $ids as $key=>$value ) {
			$value = trim ( preg_replace ( '/\D/', '', $value ) );
			if (! $value ) unset($ids[$key]);
			else $ids[$key] = $value;
		}
		if (! count($ids) ) return $this;
		$this->imagesId = $ids;
		return $this;
	}
	
	protected function execute() {
		$images_id = $this->imagesId;
		if (! $images_id || ! is_array($images_id)) 
			return false;
		$cache_dir = Zend_Registry::get ( 'cnf' )->cache_dir;
		$cache_dir .= "images/";
		if (! file_exists ( $cache_dir )) {
			mkdir ( $cache_dir, 0777, true );
		}
		$url_dir = str_replace ( ROOT_PATH, '', $cache_dir );
		$cache = Zen_Cache_Factory::get('images');
		
		$this->images = false;
		$alts = array();

		foreach ( $images_id as $image_id ) {
			$cache_id = $image_id . '_' . md5 (serialize ( $this->actions ).$this->quality.$image_id);
			$image = $cache->load($cache_id);
			if (! $image) {
				$imageModel = new Images_Model_Imageslist();
				$image = $imageModel->getTable()->find($image_id)->current ();
				$image = $image->toArray();
				if (! $image) {
					return false;
				}
			}
			$alts[$image['id']] = $image['alt'];
			
			$type=$image['type'];
			$image_name = $cache_dir . $cache_id . '.' . $type;
			$image_url = $url_dir . $cache_id . '.' . $type;
			
			if ($this->actions) {
				$image['img_url'] = $image_url;
			}
			
			if (! file_exists ( $image_name )&&(file_exists( ROOT_PATH . $image['path']))) {
				if (sizeof ( $this->actions ) > 0) {
					
					$Wimage = WideImage::load ( ROOT_PATH . $image['path'] );
					foreach ( $this->actions as $action ) {
						$make=true;
						/*
						 * Условия для $crop
						 */
						if(($action ['method']=='crop')&&(sizeof($action ['args'])==0)){
							if($image['crop']!=""){
								$cropParams=Zend_Json_Decoder::decode($image['crop']);
								$params=array(
									$cropParams['perc_x']."%",
									$cropParams['perc_y']."%",
									$cropParams['perc_width']."%",
									$cropParams['perc_height']."%",
								);
								$action ['args']=$params;
							}else{
								$make=false;
							}
						}
						/*
						 * Условия для $merge
						 */
						if(($action ['method']=='merge')){
							$action ['args'][0]=WideImage::load($action ['args'][0]);
						}
						if ($Wimage&&($make==true)) {
							if (method_exists ( $Wimage, $action ['method'] )) {
								$Wimage = call_user_func_array ( array ($Wimage, $action ['method'] ), $action ['args'] );
							}
						}
					}
					$image['width'] = $Wimage->getWidth ();
					$image['height'] = $Wimage->getHeight ();
					if ($type == "png") {
						$Wimage->saveToFile ( $image_name );
					}
					if ($type == "jpg") {
						$Wimage->saveToFile ( $image_name, $this->quality );
					}
					if ($type == "gif") {
						$Wimage->saveToFile ( $image_name );
					}
				}else{
					copy(ROOT_PATH . $image['path'], $image_name);
				}
				$image['img_url'] = $image_url;
				$cache->save($image,$cache_id,array($image_id));
				chmod($image_name, 0777);
			}
			$this->setAlts($alts);
			$this->images[] = $cache->load($cache_id);
			if ( $this->getFirstOnly() ) break;
		}
	}
	
	public function render($params=false) {
		$this->execute();
		$images = $this->images;
		if (! $images) return false;
		$html_imgs = array();
		foreach ( $images as $image ) {
			if (isset ( $image['alt'] )&&(!isset($params['alt']))) {
				$alt = 'alt="' . $image['alt'] . '"';
			} else {
				if(!isset($params['alt'])){
					$alt = 'alt=""';
				}
				else{
					$alt = 'alt="' . $params['alt'] . '"';
				}
			}
			if (isset ( $image['width'] ) && $this->getShowDim()) {
				$width = 'width="' . $image['width'] . '"';
			} else {
				$width = '';
			}
			if (isset ( $image['height'] ) && $this->getShowDim()) {
				$height = 'height="' . $image['height'] . '"';
			} else {
				$height = '';
			}
			
			if (isset ( $params['class'] )) {
				$class = 'class="' . $params['class'] . '"';
			} else {
				$class = '';
			}
			$img = '<img ' . $class . ' '. $alt . ' ' . $width . ' ' . $height . ' src="' . $image['img_url'] . '"  />';
			$img = preg_replace ( '/\040+/', ' ', $img);
			$html_imgs[] = $img;
		}
		if ( $this->getFirstOnly() ) return $html_imgs[0];
		return $html_imgs;
	}
	
	public function __call($method, $args) {
		$this->actions [] = array ('method' => $method, 'args' => $args );
		return $this;
	}
	
	
	public function getPageCount() {
		return $this->pagecount;
	}
	
	public function setPage() {
		return $this->page;
	}
	
	/**
	 * @return the $url
	 */
	public function getUrls() {
		$this->execute();
		$images = $this->images;
		if (! $images) return false;
		$urls = array();
		foreach ($images as $image) {
			$urls[$image['id']] = $image['img_url'];
		}
		if ( $this->getFirstOnly() && $urls) return $urls[0];
		return $urls;
	}
	
	/**
	 * @return the $type
	 */
	public function getType() {
		return $this->type;
	}
	
	/**
	 * @return the $quality
	 */
	public function getQuality() {
		return $this->quality;
	}
	
	/**
	 * @param field_type $type
	 */
	public function setType($type) {
		$this->type = $type;
	}
	
	/**
	 * @param field_type $quality
	 */
	public function setQuality($quality) {
		$this->quality = $quality;
	}
	
	public function setFirstOnly($value) {
		$this->first_only = $value;
		return $this;
	}
	
	public function getFirstOnly() {
		return $this->first_only;
	}
	
	public function setShowDim($value) {
		$this->show_dim = $value;
		return $this;
	}
	
	public function getShowDim() {
		return $this->show_dim;
	}
	
	public function setWatermark($wm_url = false) {
		if (! $wm_url) {
			$settings = Zen_Settings::get('images', 'settings' );
			if (! $settings ) return $this;
			if (! isset($settings['images']) || ! $settings['images'] ) return $this;
			$helper = new Zen_View_Helper_Image_Multi();
			$wm_url=$helper->image_Multi($settings['images'])->setFirstOnly(true)->getUrls();
		}
		$this->merge(ROOT_PATH.$wm_url, "left + 10", "bottom - 10");
		return $this;
	}
	
	public function getUrl() {
		$urls = $this->getUrls();
		if (! $urls) 
			return '';
		else {
			//$url = array_shift($urls);
			//return $url;
			return array_shift($urls);
		}
	}
	
	public function getAlts() {
		return $this->alts;
	}
	
	protected function setAlts($value) {
		$this->alts = $value;
		return $this;
	}

}